<?php

namespace App\Console\Commands;

use App\Http\Models\Mysql\NnyyUserTable;
use App\Http\Models\Mysql\SsyFeishuUserJsTable;
use App\Http\Models\Mysql\SsyFeishuUserMzTable;
use App\Http\Models\Mysql\SsyFeishuUserQyxTable;
use App\Http\Models\Mysql\SsyFeishuUserTable;
use App\Http\Models\Mysql\SsyFeishuUserXmTable;
use App\Http\Models\Mysql\SsyFeishuUserYxTable;
use App\Http\Models\Mysql\SsyProcessingFactoryUserTable;
use App\Http\Models\Mysql\SsyUserTable;
use Illuminate\Console\Command;

class pullUsers extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:pull-users {--extra=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '拉取飞书、工厂表用户信息';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        //补充历史人员数据
        $extraName = $this->option("extra") ?? "";
        if(!empty($extraName)){
            $this->pullSsyUser($extraName);
            die();
        }
        //同步飞书用户信息
        $this->pullFeishu("kz");
        $this->pullFeishu("yx");
        $this->pullFeishu("xm");
        $this->pullFeishu("js");
        //同步加工厂用户
        //$this->pullFactoryUser();
    }

    public function pullSsyUser($name)
    {
        $userObj = (new SsyUserTable())->where('username', $name)->first();
        if(empty($userObj)){
            echo "用户不存在, 请手动处理吧\n";
            die();
        }
        if(empty($userObj->phone)){
           echo "用户联系方式为空, 请手动处理\n";
           die();
        }
        $exist = (new NnyyUserTable())->where('name', $userObj->username)->where('phone', $userObj->phone)->first();
        if(!empty($exist)){
            echo "用户已补充, 无需处理\n";
            die();
        }
        $data = [
            'id' => $userObj->id,
            'name' => $userObj->username,
            'phone' => $userObj->phone,
            'password' => bcrypt($userObj->phone),
            'create_time' => date('Y-m-d H:i:s'),
            'status' => 0,//禁用
            'source_from' => 'fs'
        ];
        $res = (new NnyyUserTable())->createData($data);
        if($res['code'] === 0){
            echo "补充成功\n";
        }else{
            echo "失败, ".($res['data']??"")."\n";
        }
    }

    public function pullFeishu($sub = "kz")
    {
        $list = [];
        $field = ['name', 'mobile', 'status', 'user_id', 'union_id', 'open_id'];
        $endMsg = "";
        if($sub == "kz"){
            $list = (new SsyFeishuUserTable())->select($field)->get()->toArray();
            echo "同步年年有余飞书用户\n";
            $endMsg = "年年有余飞书用户, 完成同步：";
        }
        if($sub == "yx"){
            $list = (new SsyFeishuUserYxTable())->select($field)->get()->toArray();
            echo "同步有香飞书用户\n";
            $endMsg = "有香飞书用户, 完成同步：";
        }
        if($sub == "xm"){
            $list = (new SsyFeishuUserXmTable())->select($field)->get()->toArray();
            echo "同步弦木飞书用户\n";
            $endMsg = "弦木飞书用户, 完成同步：";
        }
        if($sub == "js"){
            $list = (new SsyFeishuUserJsTable())->select($field)->get()->toArray();
            echo "同步锦瑟飞书用户\n";
            $endMsg = "锦瑟飞书用户, 完成同步：";
        }
        $total = count($list);
        $num = 0;
        foreach($list as $i => $item){
            $mobile = substr($item['mobile'], 3);
            $status = json_decode($item['status'], true);
            $isResigned = $status['is_resigned'] ? true : false;//离职
            $name = trim($item['name']);
            $name = $name == "雷国亮" ? "雷聪" : $name;
            $user = (new NnyyUserTable())->where(['name' => $name, 'phone' => $mobile])->first();
            $user = !empty($user) ? $user->toArray() : [];
            echo ($i+1)."/$total 同步中: $name ";
            $data = [
                "{$sub}_feishu_user_id" => $item['user_id'],
                "{$sub}_feishu_union_id" => $item['union_id'],
                "{$sub}_feishu_open_id" => $item['open_id']
            ];
            if(!empty($user)){
                echo "更新飞书id, 当前用户：".($isResigned?"已离职":"在职")."\n";
                $data = array_merge($data, ['status' => $isResigned ? 0 : 1]);
                (new NnyyUserTable())->updateData($user['id'], $data);
            }else{
                if($isResigned){//离职
                    echo "用户已离职, 无需创建\n";
                    continue;
                }
                $data = array_merge($data, [
                    'name' => $name,
                    'phone' => $mobile,
                    'password' => bcrypt($mobile),
                    'create_time' => date('Y-m-d H:i:s'),
                    'source_from' => 'fs'
                ]);
                $res = (new NnyyUserTable())->createData($data);
                if($res['code'] === 0){
                    echo "用户创建成功\n";
                }else{
                    echo "用户创建失败, ".($res['data']??"")."\n";
                }
            }
            $num += 1;
        }
        echo $endMsg.$num."\n";
    }

    //拉取C端工厂用户数据
    public function pullFactoryUser()
    {
        $list = (new SsyProcessingFactoryUserTable())->select(['name', 'phone', 'status'])->where('status', 0)->get()->toArray();
        echo "同步工厂端用户\n";
        $total = count($list);
        $num = 0;
        foreach($list as $i => $item){
            $phone = $item['phone'];
            $name = trim($item['name']);
            $user = (new NnyyUserTable())->where(['name' => $name, 'phone' => $phone, 'source_from' => 'gc'])->first();
            $user = !empty($user) ? $user->toArray() : [];
            echo ($i+1)."/$total 同步中: $name\n";
            if(empty($user)){
                $data = [
                    'name' => $name,
                    'phone' => $phone,
                    'password' => bcrypt($phone),
                    'create_time' => date('Y-m-d H:i:s'),
                    'source_from' => 'gc'
                ];
                (new NnyyUserTable())->createData($data);
            }
            $num += 1;
        }
        echo "工厂端用户, 完成同步：$num\n";
    }
}
